const fs = require('fs');
const path = require('path');
const { fileDisplay } = require('./fileDisplay.js');
const { locale } = require('./locale.js');

const runDeleteLocaleJs = () => {
  let logText = '';
  const localeKeys = Object.keys(locale);

  // 全文件搜索的路径
  const filePath = path.resolve('./src');

  const logPath = './scripts/log.csv';

  fs.writeFile(logPath, '文件路径,keys', 'utf-8', (err) => {
    if (err) {
      console.log(err);
    } else {
      console.log('清空日志');
    }
  });

  function deleteLocaleJs(curPath) {
    if (/src\\locale\\strings/.test(curPath) || /utils\\locale/.test(curPath)) {
      console.log('跳过文件：', curPath);
      // 跳过src/locale/string的检测, 跳过utils.locale的检测
      return;
    }
    let data = fs.readFileSync(curPath, 'utf-8');
    if (data.indexOf("import locale from 'utils/locale.js'") !== -1) {
      const useKey = [];
      localeKeys.forEach((key) => {
        if (data.indexOf(`locale.${key}`) !== -1) {
          useKey.push(`locale.${key}`);
          const reg = new RegExp(`locale\\.${key}([^a-zA-Z_])`, 'g');
          data = data.replace(reg, `${locale[key]}$1`);
        }
      });
      fs.writeFile(curPath, data, 'utf-8', (err) => {
        if (err) {
          console.log(err);
        } else {
          console.log('写入文件：', curPath);
          if (!useKey.length) {
            useKey.push('引入了locale却没有使用, 存在无用注释');
          }
          logText += `${curPath}, ${useKey.join('&')}\n`;
        }
      });
    }
  }

  fileDisplay(filePath, deleteLocaleJs);

  setTimeout(() => {
    fs.writeFile(logPath, logText, 'utf-8', (err) => {
      if (err) {
        console.log(err);
      } else {
        console.log('生成日志');
      }
    });
  }, 10000);
};

module.exports = {
  runDeleteLocaleJs,
};
